#!/usr/bin/env bash
env_h_gen() {
    echo "#ifndef _ENV_H" > ./env.h
    echo "#define _ENV_H" >> ./env.h

    OSNAME=`uname -s`
    if [[ "FreeBSD" == $OSNAME ]]; then
        echo "#define _OS_FREEBSD">>./env.h
    elif [[ "Linux" == $OSNAME ]]; then
        echo "#define _OS_LINUX">>./env.h
    else
        echo "#define _OS_OTHER">>./env.h
    fi

    echo "#define _UNIT_TEST_USER \"`whoami`\"" >>./env.h
    #echo "#define _RELEASE" >>./env.h

    echo "#endif //_ENV_H">>./env.h
}

################################################################
################################################################

if [[ 0 -eq `echo $0 | grep -c '^/'` ]]; then
    # relative path
    EXEC_PATH=$(dirname "`pwd`/$0")
else
    # absolute path
    EXEC_PATH=$(dirname "$0")
fi

cd $EXEC_PATH || exit 1

env_h_gen
CC=`which clang` || CC=`which gcc` || exit 1

# include path #
perlcode='if($_=~/(?<=HOME \+ '\'')(.*)(?='\'',)/){print("$1\n")}'
for inc in $(cat $(dirname `pwd`)/.ycm_extra_conf.py | perl -ane "$perlcode"); do
    INCLUDE=${INCLUDE}" -I${HOME}$inc"
done

# clean old cc-files
make clean

# make module
SOCCFLAGS='-shared -g -O2 -std=c99 -Wall -Wextra -fvisibility=hidden -fPIC'
for x in `find $EXEC_PATH -name "GNUmakefile"`; do
    dir=`dirname $x`
    name=`basename $dir`
    cd $dir || exit 1
    gmake NAME=$name CC="$CC" SOCCFLAGS="$SOCCFLAGS" INCLUDE_PATH="$INCLUDE" || exit 1
done
cd $EXEC_PATH || exit 1

# dylib[.so] path
# MUST search current dir first!!!!
for lib in $(find `pwd` -name "*.so"); do
    DYLIB=${DYLIB}" $lib"
done
# then, search third-party libs
for lib in $(find $(dirname `pwd`)/third-party -name "*.so" | grep -v '____build____'); do
    DYLIB=${DYLIB}" $lib"
done

CCFLAGS='-g -O2 -std=c99 -Wall -Wextra -fvisibility=hidden -Wl,--as-needed'
gmake CC="$CC" \
    CCFLAGS="$CCFLAGS" \
    INSTALL_PATH="$(dirname `pwd`)/bin" \
    INCLUDE_PATH="$INCLUDE" \
    DYLIB_PATH="$DYLIB"

